﻿using Microsoft.Extensions.Configuration;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using ServiceCore.Tool.Dapper;
using ServiceCore.Tool.ES;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ServiceCore.Tool.Mqtt
{

    public interface IRK_Mqtt
    {
        void StartListenMqtt();
        System.Threading.Tasks.Task RefreshSLot(string sn);
        System.Threading.Tasks.Task Publish(string topic, string data, MqttQualityOfServiceLevel mqttQualityOfServiceLevel);
    }
    public class RK_Mqtt: IRK_Mqtt
    {

        private static object obj1 = new object();
        private static object obj = new object();
        private static IMqttClient _mqttClient;
        private readonly IConfiguration AppSettingConfig;
        private readonly IEs_Log_Helper _esService;
        private readonly IDapper_Helper _dapperService;
        private readonly ISnowflake_Helper _snowflakeService;
        public RK_Mqtt(IConfiguration configuration, IEs_Log_Helper esService, IEmqMongo_Service empMongoService, IDapper_Helper dapperService, ISnowflake_Helper snowflakeService)
        {
            AppSettingConfig = configuration;
            _esService = esService;
            _dapperService = dapperService;
            _snowflakeService = snowflakeService;
        }

        public string MQTTSERVER { get { return AppSettingConfig["aliyunMqtt:url"]; } }
        public string MQTTUSERNAME { get { return AppSettingConfig["aliyunMqtt:username"]; } }
        public string MQTTPWD { get { return AppSettingConfig["aliyunMqtt:pwd"]; } }
        public string MQTTID { get { return AppSettingConfig["aliyunMqtt:serverid"]; } }
        public string MQTTGROUPID { get { return AppSettingConfig["aliyunMqtt:groupid"]; } } 
        /// <summary>
        ///  定义个mqtt连接
        /// </summary>
        public IMqttClient mqttClient
        {
            get
            {
                if (_mqttClient == null)
                {
                    lock (obj)
                    {
                        MqttFactory factory = new MqttFactory();
                        _mqttClient = factory.CreateMqttClient();
                        return _mqttClient;
                    }
                }
                else
                {
                    return _mqttClient;
                }
            }
        }
         
        /// <summary>
        /// 定义MQTT连接属性
        /// </summary>
        public IMqttClientOptions mqttOption
        {
            get
            {
                var options = new MqttClientOptionsBuilder().WithTcpServer(MQTTSERVER, 1883)
            .WithClientId(MQTTID).WithCredentials(MQTTUSERNAME, MQTTPWD)
            .WithCleanSession()
            .Build();
                return options;
            }
        }
         
        /// <summary>
        /// 手动开始一次mqtt连接
        /// </summary>
        public async void Start()
        {
            var result = await mqttClient.ConnectAsync(mqttOption);
            Console.WriteLine($"启动程序启动了=>{Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
        } 
        /// <summary>
        /// 开始mqtt连接监听
        /// </summary>
        public async void StartListenMqtt()
        {
            MqttStart();
            while (true)
            {
                try
                {
                    if (!mqttClient.IsConnected)
                    {
                        try
                        {
                            var result = await mqttClient.ConnectAsync(mqttOption);
                            Console.WriteLine($"监听程序启动了=>{Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        Thread.Sleep(3000);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    Thread.Sleep(1);
                }
            }
        }
        private void MqttStart()
        {
            mqttClient.Connected += (object sender, MqttClientConnectedEventArgs e) =>
            {
               
                Console.WriteLine($"连接成功");
            }; 
            mqttClient.Disconnected += (object sender, MqttClientDisconnectedEventArgs e) =>
            {
                Console.WriteLine($"连接断开");
            }; 
            mqttClient.ApplicationMessageReceived += (object sender, MqttApplicationMessageReceivedEventArgs e) =>
            {

                string topic = e.ApplicationMessage.Topic;
                string data = System.Text.Encoding.Default.GetString(e.ApplicationMessage.Payload); 
                string LogPath = "/AliyunMqtt/" + topic.Replace("/", "."); 
                //Common.Log.Logger.writeLog($"topic ={topic},data ={data},datetime={System.DateTime.Now.ToString()}", LogPath);
            };
        }
        public System.Threading.Tasks.Task RefreshSLot(string sn)
        {

            string topic = $"rkt/mch/{sn}/refreshslot/";
            string now = System.DateTime.Now.ToString(); 
            return mqttClient.PublishAsync(topic, now, MqttQualityOfServiceLevel.AtLeastOnce);
        }  
        public System.Threading.Tasks.Task Publish(string topic, string data, MqttQualityOfServiceLevel mqttQualityOfServiceLevel)
        {

            if (mqttClient != null)
            {

                if (mqttClient.IsConnected)
                {  
                    return mqttClient.PublishAsync(topic, data, mqttQualityOfServiceLevel);
                }
            }
            return null;
        }

    }
}
